<template>
	<wsPage :title="$t('Permission.depManagement')">
		<div slot="page_operate">
			<Button type="ghost" @click="refresh"><Icon type="refresh"></Icon><span>{{$t('Permission.refresh')}}</span></Button>
		</div>
		
		<wsSmPanel :page="table.page" @simple-query="init" @page-change="init">
			<div slot="list_operate">
				<Button @click="showAddModal">{{$t('Permission.add')}}</Button>
			</div>
			<div slot="list_data">
				<Table :columns="table.columns" :data="table.datas"></Table>
			</div>
		</wsSmPanel>
		
		<!--新增弹框-->
		<wsModal v-model="modal1.show" :ok-text="$t('Permission.save')" :cancelText="$t('Permission.cancel')"  :title="$t('Permission.NewDepartment')" @on-ok="saveModal1" @on-cancel="cancelModal1">
		    <Form ref="modal1" :model="modal1.model" :rules="modal1.rules" :label-width="100">
		        <FormItem :label="$t('Permission.depName')" prop="name">
		            <Input v-model="modal1.model.name" :placeholder="$t('Permission.enterDepName')" autofocus/>
		        </FormItem>
		        <FormItem :label="$t('Permission.funDescription')" prop="wDesc">
		            <Input type="textarea" v-model="modal1.model.wDesc" :placeholder="$t('Permission.improveFunDesc')"/>
		        </FormItem>			        
		    </Form>			
		</wsModal>	
		<!--设置权限-->
		<wsModal v-model="modal2.show" :width="750" :ok-text="$t('role.save')" :cancelText="$t('role.cancel')"  :title="$t('role.SettingPermissions')" @on-ok="saveModal2" @on-cancel="cancelModal2">
		    <Form ref="modal2" :model="modal2.model" :label-width="100">
		    	<FormItem :label="$t('role.AllFeatures')" class="operms-form-row">
		    		<Checkbox :value="modal2.model.checkAll" @on-change="handleCheckAll">{{$t('role.selectAll')}}</Checkbox>
		    	</FormItem>	
		    	<CheckboxGroup v-model="modal2.model.permIds">
		    		<template v-for="rowItem in modal2.datas">
		    			<FormItem :label="rowItem.name" class="operms-form-row">
				    		<Row>
				            	<Col :span="4" v-for="item in rowItem.perms"><Checkbox :label="item.key">{{item.label}}</Checkbox></Col>
				            </Row>
				    	</FormItem>	
		    		</template>
		        </CheckboxGroup>
		    </Form>			
		</wsModal>			
	</wsPage>
</template>

<script>
	import Util from '../../../common/util.js';
	const validateTrim = (rule, value, callback) => {
        if (value.trim().length === 0) {
            callback(new Error('不能全部为空格'));
        } else {
            callback();
        }
    };
	export default {
		data() {
			return {
				table: {
					columns: [{
						title: '部门名称',
						key: 'name'
					},
					{
						title: '职能描述',
						key: 'wDesc',
						ellipsis: true
					},
					{
						title: '成员数量',
						width: 100,
						align: 'center',
						render: (h, params) => {
							return h('a', {
								
							}, params.row.accountNum)
						}
					},
					{
						title: '创建时间',
						key: 'createDateStr',
						width: 170,
					},
					{
						title: '操作',
						align: 'center',
						fixed: 'right',
						width: 165,
						render: (h, params) => {
                            return h('div', [
                            	h('Button', {
                                    props: {
                                        type: 'text',
                                        size: 'small'
                                    },
                                    on: {
                                    	click: () => {
                                    		this.showPermsModal(params.row);
                                    	}
                                    }
                                }, '权限设置'),
                                h('Button', {
                                    props: {
                                        type: 'text',
                                        size: 'small'
                                    },
                                    on: {
                                    	click: () => {
                                    		this.showEditModal(params.row);
                                    	}
                                    }
                                }, '编辑'),
                                h('Button', {
                                    props: {
                                        type: 'text',
                                        size: 'small'
                                    },
                                    on: {
                                    	click: () => {
                                    		let row_ = params.row;
                                    		this.delConfirm(row_);
                                    	}
                                    }
                                }, '删除')
                            ]);
                        }
					}],
					page: {
	            		total: 0, //总条数
						pageNum: 1, //当前页
						pageSize: 10 //每页显示条数
	            	},
					datas: [],
					selectedRow: null
				},
				//新增弹框
				modal1: {
					show: false,
					title: '添加部门',
					model: {
						id: '',
						name: '',
						wDesc: ''
					},
					rules: {
						name: [
							{ required: true, message: '请输入部门名称'},
							{ validator:validateTrim,message:'部门名称不能为空',trigger:'blur'}
						]
					}
				},
				//权限选择
				modal2: {
					show: false,
					model: {
						permIds: [],
						checkAll: false
					},
					datas: [],
					allOpermIds: [] //所有的权限编号集合
				}
			}
		},
		computed: {
			/**
			 * 当前的modal1是否为编辑状态
			 */
		    isEdit() {
		      return !Util.vad.isBlank(this.modal1.model.id);
		    },
		    /**
		     * 选中的权限长度
		     */
		    checkedPermIdLength() {
		    	return this.modal2.model.permIds.length;
		    }
		},
		watch: {
			'checkedPermIdLength': function(val, oldVal) {
				let allOpermIdLength_ =  this.modal2.allOpermIds.length;
				this.modal2.model.checkAll = val === allOpermIdLength_ ? true : false;
			}
		},
		mounted() {
			this.init();
			// 当前选择的语言版本
			let getCurrentLanguage=localStorage.getItem('currentLanguage');
			this.$i18n.locale=getCurrentLanguage;
			if(this.$i18n.locale=='en'){
				this.table.columns=[
					{
						title: 'Department name',
						key: 'name'
					},
					{
						title: 'Function description',
						key: 'wDesc',
						ellipsis: true
					},
					{
						title: 'Number of members',
						width: 100,
						align: 'center',
						render: (h, params) => {
							return h('a', {
								
							}, params.row.accountNum)
						}
					},
					{
						title: 'Creation time',
						key: 'createDateStr',
						width: 170,
					},
					{
						title: 'operating',
						align: 'center',
						fixed: 'right',
						width: 165,
						render: (h, params) => {
                            return h('div', [
                            	h('Button', {
                                    props: {
                                        type: 'text',
                                        size: 'small'
                                    },
                                    on: {
                                    	click: () => {
                                    		this.showPermsModal(params.row);
                                    	}
                                    }
                                }, 'Permission settings'),
                                h('Button', {
                                    props: {
                                        type: 'text',
                                        size: 'small'
                                    },
                                    on: {
                                    	click: () => {
                                    		this.showEditModal(params.row);
                                    	}
                                    }
                                }, 'edit'),
                                h('Button', {
                                    props: {
                                        type: 'text',
                                        size: 'small'
                                    },
                                    on: {
                                    	click: () => {
                                    		let row_ = params.row;
                                    		this.delConfirm(row_);
                                    	}
                                    }
                                }, 'delete')
                            ]);
                        }
					}
				];

				this.modal1.rules={
					name: [
							{ required: true, message: 'Please enter the department name'},
							{ validator:validateTrim,message:'Department name cannot be empty',trigger:'blur'}
						]
				};						

			}else if(this.$i18n.locale=='it'){
				this.table.columns=[
					{
						title: 'Nome del dipartimento',
						key: 'name'
					},
					{
						title: 'Descrizione della funzione',
						key: 'wDesc',
						ellipsis: true
					},
					{
						title: 'Numero di membri',
						width: 100,
						align: 'center',
						render: (h, params) => {
							return h('a', {
								
							}, params.row.accountNum)
						}
					},
					{
						title: 'Tempo di creazione',
						key: 'createDateStr',
						width: 170,
					},
					{
						title: 'operativo',
						align: 'center',
						fixed: 'right',
						width: 165,
						render: (h, params) => {
                            return h('div', [
                            	h('Button', {
                                    props: {
                                        type: 'text',
                                        size: 'small'
                                    },
                                    on: {
                                    	click: () => {
                                    		this.showPermsModal(params.row);
                                    	}
                                    }
                                }, 'Impostazioni di autorizzazione'),
                                h('Button', {
                                    props: {
                                        type: 'text',
                                        size: 'small'
                                    },
                                    on: {
                                    	click: () => {
                                    		this.showEditModal(params.row);
                                    	}
                                    }
                                }, 'Modifica'),
                                h('Button', {
                                    props: {
                                        type: 'text',
                                        size: 'small'
                                    },
                                    on: {
                                    	click: () => {
                                    		let row_ = params.row;
                                    		this.delConfirm(row_);
                                    	}
                                    }
                                }, 'cancellato')
                            ]);
                        }
					}
				];

				this.modal1.rules={
					name: [
							{ required: true, message: 'Si prega di inserire il nome del dipartimento'},
							{ validator:validateTrim,message:'Il nome del dipartimento non può essere vuoto',trigger:'blur'}
						]
				}

			}


		},
		methods: {
			/**
			 * 初始化
			 */
			init() {
				const _this = this;
				let pageSize_ = this.table.page.pageSize;
				let pageNum_ = this.table.page.pageNum;
				this.axios.get('/ws/sys/new/roles/' + pageSize_ + '/' + pageNum_).then(function(response) {
					let res = response.data;
					if(0 === res.meta.code) {
						_this.buildTableData(res.data);
					} else {
						_this.$Message.error('数据查询失败!');
					}
				});
			},
			/**
			 * 刷新
			 */
			refresh() {
				this.table.page = {
            		total: 0, //总条数
					pageNum: 1, //当前页
					pageSize: 10 //每页显示条数
            	};
            	this.init();
			},
			/**
			 * 构建表格数据
			 */
			buildTableData(data_) {
				this.table.page = {
					total: data_.total, //总条数
					pageNum: data_.pageNum, //当前页
					pageSize: data_.pageSize //每页显示条数
				};
				this.table.datas = data_.list;
				console.log(this.table.datas);
			},
			/**
			 * 显示新增弹框
			 */
			showAddModal() {
				this.modal1.show = true;
				this.modal1.title = '新增部门';
				this.initAdd();
			},
			/**
			 * 初始化新增MODAL
			 */
			initAdd() {
				this.modal1.model = {
					id: '',
					name: '',
					wDesc: ''
				};
			},
			/**
			 * 显示编辑弹框
			 */
			showEditModal(row_) {
				this.modal1.show = true;
				this.modal1.title = '编辑部门';
				this.initEdit(row_);
			},
			/**
			 * 编辑部门
			 */
			initEdit(row_) {
				const _this = this;
				let cId_ = row_.id;
				let rsv_ = row_.rsv_;
				this.axios.get('/ws/sys/role/' + cId_ + '/' + rsv_).then(function(response) {
					let res = response.data;
					if(0 === res.meta.code) {
						_this.buildEditData(res.data);
					} else {
						let message_ = res.meta.message;
						_this.$Message.warning('初始化编辑操作失败:' + message_);
					}
				});					
			},
			/**
			 * 初始化编辑内容
			 */
			buildEditData(data_) {
				this.modal1.model = {
					id: data_.id,
					name: data_.name,
					wDesc: data_.wDesc
				};
			},
			/**
			 * 保存弹框1内容
			 */
			saveModal1() {
				this.$refs['modal1'].validate((valid) => {
                    if (valid) {
                        this.submitModal1();
                    } 
                });			
			},
			/**
			 * 提交表单
			 */
			submitModal1() {
				if(this.isEdit) {
					this.editDataDict();
				} else {
					this.saveDataDict();
				}
			},
			/**
			 * 保存数据字典
			 */
			saveDataDict() {
				let postData_ = this.modal1.model;
				const _this = this;
				this.axios.post('/ws/sys/roles', postData_).then(function(response) {
					let res = response.data;
					if(0 === res.meta.code) {
						_this.$Message.success('新增部门成功');
						_this.cancelModal1();
						_this.init();
					} else {
						let message_ = res.meta.message;
						_this.$Message.warning('新增部门失败:' + message_);
					}
				});
			},
			/**
			 * 编辑数据字典
			 */
			editDataDict() {
				let postData_ = this.modal1.model;
				const _this = this;
				this.axios.put('/ws/sys/roles', postData_).then(function(response) {
					let res = response.data;
					if(0 === res.meta.code) {
						_this.$Message.success('修改部门成功');
						_this.cancelModal1();
						_this.init();
					} else {
						let message_ = res.meta.message;
						_this.$Message.warning('修改部门失败:' + message_);
					}
				});
			},
			/**
			 * 取消弹框1
			 */
			cancelModal1() {
				this.$refs['modal1'].resetFields();
				this.modal1.show = false;
			},
			/**
			 * 删除提示
			 */
			delConfirm(row_) {
				const _this = this;
				if(_this.$i18n.locale=='zh'){
					this.$confirm({
						title: '操作提示',
						width: 300,
						content: '你确认删除本行记录吗?',
						onOk: function() {
							_this.delDatadictRow(row_);
						}
					});	
				}else if(_this.$i18n.locale=='en'){
					this.$confirm({
						title: 'Alert',
						width: 300,
						content: 'Delete your bank records?',
						onOk: function() {
							_this.delDatadictRow(row_);
						}
					});
				}
							
			},
			/**
			 * 删除数据字典项目
			 */
		    delDatadictRow(rowItem_) { //删除行
		      let datadictId = rowItem_.id;
		      let rsv_ = rowItem_.rsv_;
		      const _this = this;
		      this.axios.delete('/ws/sys/new/role/' + datadictId + '/' + rsv_).then(function(response) {
		      		let res = response.data;
					if(0 === res.meta.code) {
						_this.$Message.success('删除记录成功');
						_this.init();
					} else {
						let message_ = res.meta.message;
						_this.$Message.warning('删除部门失败:' + message_);
					}
		      });
		    },
		    /**
		     * 显示权限编辑菜单
		     */
		    showPermsModal(row_) {
		    	this.modal2.show = true;
		    	this.table.selectedRow = row_;
				this.initPermsModal(row_);
		    },
		    /**
		     * 初始化权限模态框
		     */
		    initPermsModal(row_) {
		    	this.modal2.model.permIds = [];
		    	const _this = this;
		    	let rId_ = row_.id;
		    	let rsv_ = row_.rsv_;
				this.axios.get('/ws/sys/role/permissions/' + rId_ + '/' + rsv_+'/'+localStorage.getItem('currentLanguage')).then(function(response) {
					let res = response.data;
					if(0 === res.meta.code) {
						_this.buildModal2Data(res.data);
					} else {
						let message_ = res.meta.message;
						_this.$Message.warning('初始化角色权限列表失败:' + message_);
					}
				});						    	
		    },
		    /**
		     * 构建模态框2的数据
		     */
		    buildModal2Data(data_) {
				console.log(data_);
		    	this.modal2.datas = data_.datas;
		    	this.modal2.model.permIds = data_.permIds;
		    	this.buildAllPermsIds();
		    },
		    /**
		     * 构造所有的权限索引集合
		     */
		    buildAllPermsIds() {
		    	let datas_ = this.modal2.datas;
		    	let allOpermIds_ = [];
		    	for(let i =0 ;i < datas_.length; i++) {
		    		let perms_ = datas_[i].perms;
		    		for(let j = 0;j < perms_.length; j++) {
		    			allOpermIds_.push(perms_[j].key);
		    		}
		    	}
		    	
		    	this.modal2.allOpermIds = allOpermIds_;
		    	let permIds_ = this.modal2.model.permIds;
		    	//设置为选中
		    	if(allOpermIds_.length === permIds_.length) {
		    		this.modal2.model.checkAll = true;
		    	}
		    },
		    /**
		     * 取消模态框2
		     */
		    cancelModal2() {
		    	this.$refs['modal2'].resetFields();
				this.modal2.show = false;
		    },
		    /**
		     * 保存模态框2
		     */
		    saveModal2() {
		    	let row_ = this.table.selectedRow;
		    	const _this = this;
		    	let rId_ = row_.id;
		    	let rsv_ = row_.rsv_;
		    	let postData_ = this.modal2.model.permIds;
				this.axios.put('/ws/sys/role/permissions/' + rId_ + '/' + rsv_, postData_).then(function(response) {
					let res = response.data;
					if(0 === res.meta.code) {
						_this.$Message.success('修改部门权限成功');
					} else {
						let message_ = res.meta.message;
						_this.$Message.warning('修改部门权限失败:' + message_);
						}
				});		    	
		   },
		   /**
		    * 选中所有
		    */
		   handleCheckAll() {
		   	console.log(this.modal2.model.checkAll);
		   	let checkAll_ = this.modal2.model.checkAll;
		   	this.modal2.model.permIds = [];
		   	if(!checkAll_) {
		   		let allOpermIds_ = this.modal2.allOpermIds;
		   		for(let i = 0; i < allOpermIds_.length; i++) {
		   			this.modal2.model.permIds.push(allOpermIds_[i]);
		   		}
		   	}
		   	this.modal2.model.checkAll = !checkAll_;
		   }
		}
	}
</script>

<style scoped="scoped">
	.operms-form-row {
		margin-bottom: 5px !important;
	}
</style>